import { Injectable } from '@nestjs/common';
import { Products, sku, specs } from './products.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, ILike, FindManyOptions, In,Like } from 'typeorm';
@Injectable()
export class ProductsService {
    @InjectRepository(Products) private readonly productsRepository: Repository<Products>
    @InjectRepository(sku) private readonly skuRepository: Repository<sku>
    @InjectRepository(specs) private readonly specsRepository: Repository<specs>

    async findAll(options: any): Promise<Products[]> {
        return this.productsRepository.findBy(options);
    }
    async detail(id: number): Promise< any > {
        let sku_list: any[] = [];
        let spec_list: any[] = [];
        try {
          let res:any =  await this.productsRepository.findOneBy({ id });
          const skus =   await this.skuRepository.findBy({ product_id:id});
          const specs = await this.specsRepository.findBy({ product_id:id});
          if(skus.length > 0){
              skus.forEach((item:any) => {
                sku_list.push(item) 
              });
          }
          if(specs.length > 0){
              specs.forEach((item:any) => {
                spec_list.push(item) 
              });
          }
          return { ...res,spec_list,sku_list}
        } catch (error) {
          throw new Error('Failed to fetch menu details');
        }
      }
    async findBy(info: any): Promise<any> {
        // 校验输入参数
        if (!Array.isArray(info.merchant_id) || info.merchant_id.some((id: number) => typeof id !== 'number')) {
            throw new Error('Invalid merchant_id: must be an array of numbers');
        }

        if (typeof info.pageSize !== 'number' || info.page < 1 || info.pageSize < 1) {
            throw new Error('Invalid pagination parameters: page and pageSize must be positive numbers');
        }

        let data = JSON.parse(JSON.stringify(info));
        delete data.merchant_id;
        delete data.page;
        delete data.pageSize;

        // 构建查询条件
        let whereConditions: any = {
            merchant_id: In(info.merchant_id),
        };

        if (data.name) {
            whereConditions.name = Like(`%${data.name}%`);
            delete data.name;
        }

        whereConditions = { ...whereConditions, ...data };
        // console.log(whereConditions);
        try {
            const [posts, total] = await this.productsRepository.findAndCount({
                where: whereConditions,
                skip: (info.page - 1) * info.pageSize,
                order: {
                    status: 'DESC',
                },
                take: info.pageSize,
            });
            return {
                data: posts,
                total,
                page: info.page,
                pageSize: info.pageSize,
                // ...其他分页信息
            };
        } catch (error) {
            throw new Error('Failed to fetch dishes');
        }
    }
    async findByName(name: string): Promise<Products[]> {
        const queryOptions: FindManyOptions<Products> = {
            where: { name: ILike(`%${name}%`) } // 使用 where 指定查询条件
        };
        return await this.productsRepository.find(queryOptions);
    }

    /**
     * 新增商品及其规格和SKU信息
     * @param info - 商品信息，包含基本信息、规格列表和SKU列表
     * @returns {Promise<Products>} 返回创建的商品信息
     * @throws {Error} 创建失败时抛出错误
     */
    async add(info: any): Promise<Products> {
        const { spec_list, sku_list } = info;

        // 使用事务确保数据一致性
        const queryRunner = this.productsRepository.manager.connection.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction();

        try {
            // 创建商品实例
            const product = this.productsRepository.create(info);
            const savedProduct: any = await this.productsRepository.save(product);

            // 批量保存SKU信息
            const skuEntities = sku_list.map(skuItem => this.skuRepository.create({
                product_id: savedProduct.id,
                ...skuItem
            }));
            await queryRunner.manager.save(skuEntities);

            // 批量保存规格信息
            const specEntities = spec_list.map(specItem => this.specsRepository.create({
                product_id: savedProduct.id,
                ...specItem
            }));
            await queryRunner.manager.save(specEntities);

            // 提交事务
            await queryRunner.commitTransaction();
            return savedProduct;
        } catch (error) {
            // 回滚事务
            await queryRunner.rollbackTransaction();
            throw new Error(`新建商品失败: ${error.message}`);
        } finally {
            // 释放查询运行器
            await queryRunner.release();
        }
    }

    /**
     * 更新商品及其规格和SKU信息
     * @param {number} id - 商品ID
     * @param {any} info - 更新的商品信息，包含规格列表和SKU列表
     * @returns {Promise<any>} 返回更新结果
     * @throws {Error} 更新失败时抛出错误
     */
    async update(id: number, info: any): Promise<any> {
        const { spec_list, sku_list, ...productInfo } = info;

        // 使用事务确保数据一致性
        const queryRunner = this.productsRepository.manager.connection.createQueryRunner();
        await queryRunner.connect();
        await queryRunner.startTransaction();

        try {
            // 检查商品是否存在 - 使用queryRunner.manager保持事务一致性
            const product = await queryRunner.manager.findOneBy(Products, { id });
            if (!product) {
                throw new Error('商品不存在');
            }

            // 更新商品信息 - 使用queryRunner.manager保持事务一致性
            // 只更新Products实体中存在的字段
            const productRepository = queryRunner.manager.getRepository(Products);
            const productMetadata = productRepository.metadata;
            const productFields = productMetadata.columns.map(column => column.propertyName);

            // 过滤掉不在Products实体中定义的字段
            const filteredProductInfo = Object.keys(productInfo)
                .filter(key => productFields.includes(key))
                .reduce((obj, key) => {
                    obj[key] = productInfo[key];
                    return obj;
                }, {});

            const updateResult = await queryRunner.manager.update(Products, id, filteredProductInfo);
            if (updateResult.affected === 0) {
                throw new Error('商品更新失败');
            }

            // 删除旧的SKU信息
            const skuNow = await queryRunner.manager.find(sku, {
                where: {
                    product_id: id,
                },
            });
            if (skuNow.length > 0) {
                await queryRunner.manager.delete(sku, { id: In(skuNow.map((v) => v.id)) });
            }

            // 批量保存新的SKU信息
            const skuEntities = sku_list.map((skuItem: any) =>
                this.skuRepository.create({
                    product_id: id,
                    ...skuItem,
                })
            );
            await queryRunner.manager.save(skuEntities);

            // 删除旧的规格信息
            const specNow = await queryRunner.manager.find(specs, {
                where: {
                    product_id: id,
                },
            });
            if (specNow.length > 0) {
                await queryRunner.manager.delete(specs, { id: In(specNow.map((v) => v.id)) });
            }

            // 批量保存新的规格信息
            const specEntities = spec_list.map((specItem: any) =>
                this.specsRepository.create({
                    product_id: id,
                    ...specItem
                })
            );
            await queryRunner.manager.save(specEntities);

            // 提交事务
            await queryRunner.commitTransaction();

            return { success: true, message: '商品更新成功' };
        } catch (error) {
            // 回滚事务
            await queryRunner.rollbackTransaction();
            throw new Error(`修改商品失败: ${error.message}`);
        } finally {
            // 释放查询运行器
            await queryRunner.release();
        }
    }
}
